<template>
    <el-dialog :title="dialogText" :visible="true" width="600px" center :lock-scroll="true" top="40px"
        :close-on-press-escape="false" :close-on-click-modal="false" @close="cancel">
        <el-form label-width="160px">
            <el-form-item label="题目类型" required label-width="120px">
                <el-radio-group v-model="formData.type" @change="handleQuestionTypeChange">
                    <el-radio label="单选题">单选题</el-radio>
                    <el-radio label="多选题">多选题</el-radio>
                </el-radio-group>

            </el-form-item>

            <el-form-item label="题干" required label-width="120px">
                <el-input v-model="formData.title" placeholder="请输入题目题干" />
            </el-form-item>

            <el-form-item label="题目选项" required label-width="120px">
                <div v-for="(option, index) in formData.options" :key="index" class="option-item">
                    <el-button class="label" type="text">{{ emptyOptions[index].label }}</el-button>
                    <el-input class="value" v-model="option.value" placeholder="请填写题目选项"></el-input>
                    <el-button class="delete" type="danger" @click="removeOption(index)">删除</el-button>
                </div>
                <el-button type="text" size="small" @click.native="addOption">添加选项</el-button>
            </el-form-item>


            <el-form-item label="正确答案" required label-width="120px" v-if="boolRender">

                <template v-if="!multiple">
                    <el-select v-model="selectedAnswers" :disabled="!formData.options.length" placeholder="请选择一个答案">
                        <el-option v-for="(option, index) in formData.options" :key="index"
                            :label="emptyOptions[index].label" :value="emptyOptions[index].label"></el-option>
                    </el-select>
                </template>

                <template v-else>
                    <el-select v-model="selectedAnswers" :disabled="!formData.options.length" placeholder="选择正确答案"
                        @change="handleAnswerChange" :multiple="true">
                        <el-option v-for="(option, index) in formData.options" :key="index"
                            :label="emptyOptions[index].label" :value="emptyOptions[index].label"></el-option>
                    </el-select>
                </template>


            </el-form-item>


        </el-form>
        <span slot="footer">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="handleSubmit">保存</el-button>
        </span>
    </el-dialog>
</template>

<script>

export default {
    data() {
        return {
            emptyOptions: [
                { label: "A", value: "" },
                { label: "B", value: "" },
                { label: "C", value: "" },
                { label: "D", value: "" },
                { label: "E", value: "" },
                { label: "F", value: "" },
            ],

            typeList: [
                {
                    key: "单选题",
                    value: "单选题",
                },

                {
                    key: "多选题",
                    value: "多选题",
                },
            ],

            selectedAnswers: [],

            formData: {
                options: [],
                correctAnswers: "",
                topicId: "",
                lessonId: "",
                title: "",
                type: "单选题",

            },

            dialogVisibleType: "",
            boolRender: true
        }
    },
    computed: {
        dialogText() {
            if (this.dialogVisibleType === "edit") {
                return "编辑题目";
            }
            return "添加题目";
        },

        multiple() {
            return this.formData.type === '多选题'
        }

    },

    methods: {

        init(type, row) {
            this.dialogVisibleType = type;
            const { lessonId, topicId } = this.$route.query;
            this.formData.lessonId = lessonId;
            this.formData.topicId = topicId;



            if (type === "edit") {

                this.formData = {
                    ...this.formData,
                    ...row
                };

                if (row.type === "单选题") {
                    this.selectedAnswers = row.correctAnswers
                } else if (row.type === "多选题") {
                    this.selectedAnswers = row.correctAnswers.split("")
                }
            } else {
                this.selectedAnswers = "";
                this.formData = {
                    ...this.formData,
                    options: [
                        { label: "A", value: " " },
                        { label: "B", value: " " },
                        { label: "C", value: " " },
                        { label: "D", value: " " }
                    ],
                    correctAnswers: "",
                    title: "",
                    type: "单选题",
                };
            }
        },

        removeOption(index) {
            if (this.formData.options.length === 1) {
                return this.$message.error(`最少添加1个选项`);

            }
            this.formData.options = this.formData.options.filter((item, i) => i !== index);
        },

        addOption() {
            const len = this.formData.options.length;
            if (len >= this.emptyOptions.length) {
                return this.$message.error(`最多添加${this.emptyOptions.length}个选项`);
            }
            this.formData.options = [
                ...this.formData.options,
                this.emptyOptions[len]
            ]
        },

        handleQuestionTypeChange(val) {
            this.boolRender = false;
            if (this.multiple) {
                this.selectedAnswers = []
            } else {
                this.selectedAnswers = ""
            }
            this.$nextTick(() => {
                this.boolRender = true;
            })
        },
        handleAnswerChange(val) {

        },

        cancel() {
            this.$emit("update:visible", false);
            this.$emit("refresh")
        },

        async handleSubmit() {

            if (this.multiple) {
                this.formData.correctAnswers = this.selectedAnswers.sort().join("");
            } else {
                if (Array.isArray(this.selectedAnswers)) {
                    this.formData.correctAnswers = this.selectedAnswers[0];
                } else {
                    this.formData.correctAnswers = this.selectedAnswers;
                }
            }

            await this.$nextTick();


            let res;
            const { title, correctAnswers, options, type } = this.formData;


            const rules = [
                {
                    case: !title,
                    message: "请输入题干",
                },
                {
                    case: !correctAnswers,
                    message: "请至少选择一个正确答案",
                },
                {
                    case: correctAnswers.length === 1 && type === "多选题",
                    message: "多选择请选择多个答案",
                },
                {
                    case: options.length === 0,
                    message: "请至少添加一个选项",
                },

            ]

            const valid = this.$validForm(rules)

            if (!valid) {
                return
            }

            this.formData.options = this.formData.options.map((item, index) => {
                return {
                    ...item,
                    label: this.emptyOptions[index].label,
                };
            });

            if (this.dialogVisibleType === "edit") {
                res = await this.$fetch.post("/api/topic-lesson-question-bank/update", {
                    ...this.formData,
                });
            } else {
                res = await this.$fetch.post("/api/topic-lesson-question-bank/create", {
                    ...this.formData,
                });
            }

            if (res.code === 0) {
                this.$message.success(
                    this.dialogVisibleType === "edit" ? "修改成功" : "添加成功"
                );
            }

            this.cancel();
        },

    }
}
</script>

<style lang="less" scoped>
::v-deep .el-form-item__content {
    .option-item {
        display: flex;
        gap: 8px;
        margin-bottom: 8px;

    }
}
</style>